#############################################################################
#  Copyright (C) 2007 Boscovich, Maximiliano - mboscovich@gmail.com          #
#                                                                            #
#  This program is free software; you can redistribute it and/or modify      #
#  it under the terms of the GNU General Public License as published by      #
#  the Free Software Foundation; either version 3 of the License, or         #
#  (at your option) any later version. See tht GPL_Licence.txt for details.  #
#                                                                            #
#  This program is distributed in the hope that it will be useful,           #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of            #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the              #
#  GNU General Public License for more details.                              #
#                                                                            #
##############################################################################

import sys
sys.path.append("../")

from sqlobject import dberrors
from formencode import Invalid

from view.Distribution_view import *
from model.tables import *
import logModule

class Distribution_controller(Ui_Distribution_view):

    def __init__(self):
        self.widget = QtGui.QDialog()
        self.setupUi(self.widget)
        # Connections
        self.widget.connect(self.pushButtonOk, QtCore.SIGNAL("clicked()"), 
                            QtCore.SLOT('close()'))
        self.widget.connect(self.pushButtonAdd, QtCore.SIGNAL("clicked()"), 
                            self.addDistribution)
        self.widget.connect(self.pushButtonDelete, QtCore.SIGNAL("clicked()"),
                            self.delDistribution)
        self.load_list()
    
    # load all registers on listWidget
    def load_list(self):
        self.listWidgetDistribution.clear()
        registers = Distribution.select()
        for register in registers:
            self.listWidgetDistribution.addItem(register.Name)

    def addDistribution(self):
        dist_name = str(self.lineEditAdd_Distribution.text())
        try:
            new_distribution=Distribution(Name=dist_name)
            self.load_list()
        except Invalid,e:
            logModule.log(e)
        except dberrors.DuplicateEntryError:
            logModule.log("La distribucion "+dist_name+" ya existe")      
        
    def delDistribution(self):
        item_selected = (self.listWidgetDistribution.currentItem())
        dist_selected = str(item_selected.text())
        dist_to_delete=Distribution.selectBy(Name=dist_selected)
        self.listWidgetDistribution.takeItem(
                                    self.listWidgetDistribution.currentRow()
                                    )
        dist_to_delete[0].destroySelf()

